﻿using System;
using System.Data.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using PhoneCore.Framework;
using PhoneCore.Framework.Diagnostic.Tracing;
using PhoneCore.Framework.Storage;
using SecureBox.UI.Infrastructure.Model;

namespace SecureBox.UI.Infrastructure.Data
{
    /// <summary>
    /// Uses local database (ldf) engine as storage
    /// </summary>
    public class DataContextService : IDataContextService
    {
        private readonly SecureBoxDataContext _dataContext;
        /// <summary>
        /// Raised when Commit is called
        /// </summary>
        public event EventHandler<EventArgs> OnChanged;
        private void InvokeOnChanged(EventArgs e)
        {
            EventHandler<EventArgs> handler = OnChanged;
            if (handler != null) handler(this, e);
        }

        public DataContextService(SecureBoxDataContext dataContext)
        {
            _dataContext = dataContext;
            Templates = new TemplateRepository(dataContext);
            Records = new RecordRepository(dataContext);
            Keywords = new KeywordRepository(dataContext);
            Properties = new PropertyRepository(dataContext);
        }

        /// <summary>
        /// Templates repository
        /// </summary>
        public IRepository<Model.Template> Templates { get; private set; }

        /// <summary>
        /// Records repository
        /// </summary>
        public IRepository<Model.Record> Records { get; private set; }

        /// <summary>
        /// Keywords repository
        /// </summary>
        public IRepository<Model.Keyword> Keywords { get; private set; }

        /// <summary>
        /// Property repository
        /// </summary>
        public IRepository<Model.Property> Properties { get; private set; }

        /// <summary>
        /// Commits the changes in repositories
        /// </summary>
        public void Commit()
        {
            Templates.Commit();
            Properties.Commit();
            Keywords.Commit();
            Records.Commit();
            InvokeOnChanged(new EventArgs());
        }

        public void Delete()
        {
            if(_dataContext.DatabaseExists())
                _dataContext.DeleteDatabase();
        }

        public void Dispose()
        {
            if (_dataContext != null)
                _dataContext.Dispose();
        }
    }
}
